package hibu.LeiJonGun.activities;
import hibu.LeiJonGun.seniorservice.Assignment;
import hibu.LeiJonGun.seniorservice.Control;
import hibu.LeiJonGun.seniorservice.R;
import java.sql.Timestamp;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//Created by Elis Tor Jonsson
//All assignment activities end up to ActAssignmentSummary where the user confirm the new assignment or goes back

public class ActAssignmentSummary extends Activity implements TextWatcher{
	
	private String assignmentText;
	private String category;
	private Control control;
	private ProgressDialog dialog;
	private ArrayList<String> ArticleSelectedList;
	private EditText shoppinglistText;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.act_mission_summary, menu);
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle menu click
        switch (item.getItemId()) {
        case R.id.act_mission_summary_help:
        	String url = "http://www.lillesto.net/hjelpeside/index.html";
        	Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        	startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	startActivity();
	    	return true;
	    }
	        return super.onKeyUp(keyCode, event);
	 }

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_assignment_summary);
		
        control = ((Control)this.getApplicationContext()); 
		control.setContext(ActAssignmentSummary.this);
		shoppinglistText = (EditText) findViewById(R.id.txtShoppinglist);
		shoppinglistText.addTextChangedListener(this);
		
		final TextView lblList= (TextView) findViewById(R.id.lblListHeader);
		final ImageButton imgBtnAddList= (ImageButton) findViewById(R.id.btnAddList);		
		final TextView lblAddList= (TextView) findViewById(R.id.lblAddList);
		final LinearLayout layoutAdd = (LinearLayout) findViewById(R.id.layoutAdd);		
		final Button btnRegister = (Button) findViewById(R.id.btnRegister);

		imgBtnAddList.getBackground().setAlpha(50);
		lblAddList.setTextColor(getResources().getColor(R.color.colorBackgroundEnd));

		Intent intent = getIntent();
		//get selected category from previous activity
		category = intent.getExtras().getString("category"); 
		//get selected assignmentText from previous activity
		assignmentText = intent.getExtras().getString("assignmentText"); 
		
		final TextView lblHeader= (TextView) findViewById(R.id.lblHeader);
		lblHeader.setText("Oppdrag: " + assignmentText);
		
		setTitle(assignmentText);
		String articlesToAssignment = "";
		
		//If shopping is chosen
		if (category.equals("Handling")){ 
			imgBtnAddList.getBackground().setAlpha(255);
			lblAddList.setTextColor(getResources().getColor(R.color.lblText));
			lblList.setText("Handleliste:");
			//get ArrayList from article
			ArticleSelectedList = intent.getExtras().getStringArrayList("List"); 
			if (ArticleSelectedList.isEmpty()){
					shoppinglistText.setHint("Handlelisten er tom");
			}else{
				for (int i = 0; i < ArticleSelectedList.size(); i++){
					String article = " "+ArticleSelectedList.get(i);
					articlesToAssignment += article + ",";
				}
			}
		}
		shoppinglistText.setText(articlesToAssignment);
	 
	 final View.OnTouchListener onPressedCategory = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				String selected = v.getTag().toString();
					if (event.getAction()==MotionEvent.ACTION_DOWN) {; 
						// Check witch layout,image or text that was pressed
						if (selected.equals("addList")) {
							lblAddList.setTextColor(getResources().getColor(R.color.lblTextPressed));
							imgBtnAddList.setBackgroundResource(R.drawable.listaddpressed);
						}
					}else if(event.getAction()==MotionEvent.ACTION_UP){
						// Check which layout,image or text that was pressed
						//The add button is pressed
						if (selected.equals("addList")) {
							lblAddList.setTextColor(getResources().getColor(R.color.lblText));
							imgBtnAddList.setBackgroundResource(R.drawable.listadd);
							startActivity();
						//Register new assignment
						}else if (selected.equals("register")) {
							dialog = ProgressDialog.show(ActAssignmentSummary.this, "Vent litt", "Registrerer oppdrag");
							dialog.setCancelable(false);
							try {
								if (control.isOnline()) {
									control.addDBActiveAssignment(control.getUser().getUsername(),
											shoppinglistText.getText().toString().replace('@', 'a'),assignmentText);
								} else {
									//No internet access
									Toast t = Toast.makeText(ActAssignmentSummary.this, "Ingen internett tilgang", Toast.LENGTH_LONG);
									t.show();
								}			
							} catch (Exception e) {
								//Catch error message
								Toast t = Toast.makeText(getApplicationContext(), "Feilmelding:\n\n"+e.getMessage(), Toast.LENGTH_LONG);
								t.show();
								e.printStackTrace();
							}
						}
					}
				return true;
			}
		};
		layoutAdd.setOnTouchListener(onPressedCategory);
		imgBtnAddList.setOnTouchListener(onPressedCategory);
		lblAddList.setOnTouchListener(onPressedCategory);
		btnRegister.setOnTouchListener(onPressedCategory);
	}
		
	//Starts activity based on Category
	private void startActivity(){ 
		Intent intentSummary = null;
		//Shopping
    	if (category.equals("Handling")){
    		intentSummary = new Intent(ActAssignmentSummary.this, ActAssignmentArticle.class);
    		intentSummary.putExtra("List",ArticleSelectedList);
    		intentSummary.putExtra("done",true);
    		intentSummary.putExtra("assignmentText",assignmentText);
    		intentSummary.putExtra("category",category); 
    	}
    	//Housework
    	if (category.equals("Husarbeid")){
    		intentSummary = new Intent(ActAssignmentSummary.this, ActAssignmentHousework.class);
    		intentSummary.putExtra("category",category); 
    	}
    	//Outdoor work
    	if (category.equals("Utearbeid")){
    		intentSummary = new Intent(ActAssignmentSummary.this, ActAssignmentOutdoorwork.class);
    		intentSummary.putExtra("category",category); 
    	}
    	//Other
    	if (category.equals("Transport") || category.equals("Matlaging") || category.equals("Egendefinert") ){
    		intentSummary = new Intent(ActAssignmentSummary.this, ActAssignmentCategory.class);
    		intentSummary.putExtra("category",category); 
    	}
		startActivity(intentSummary);
		finish();
	}
	
	//Is called upon by the Control class
	public void dbWorkFinished(String result,int id, Timestamp startTime) {
		Assignment newAssignment = null;    	
		try {
			newAssignment = new Assignment(id,control.getUser(),category,startTime,assignmentText,shoppinglistText.getText().toString());
			control.addAssignment(newAssignment);
		} catch (Exception e) {
			e.printStackTrace();
		}
		dialog.dismiss();
		//Assignment registered
		Toast t = Toast.makeText(getApplicationContext(),newAssignment.getCategory() + "Oppdrag er registrert", Toast.LENGTH_LONG);
		t.setGravity(Gravity.CENTER|0, 0, 0);
		t.show();
		toMainMenu();
	}
	
	public void toMainMenu(){
		startActivity(new  Intent(ActAssignmentSummary.this, ActMainScreen.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		finish();
	}

	//Is called upon by the Control class
	public void dbWorkAborted(String error) {
		dialog.dismiss();
		//Error message
		Toast t = Toast.makeText(this, "En feil skjedde\n\n"+error, Toast.LENGTH_LONG);
		t.show();
	}
	
	@Override
    public void onResume() {
    	super.onRestart();
    	control.setContext(ActAssignmentSummary.this);
    }
	
	//Removes the char if it it's one of these: @,# or ;
	public void afterTextChanged(Editable s) {
		String letters = shoppinglistText.getText().toString();
		if (letters.toString().contains("@") || letters.toString().contains("#") || letters.toString().contains(";")){
			Toast.makeText(getApplicationContext(), "Kan ikke inneholde tegnene @,# eller ;", Toast.LENGTH_SHORT).show();
			String t = s.toString().substring(0, s.length()-1) + "";  //what it will be replaced with
			shoppinglistText.setText(t.toString()); 
			shoppinglistText.setSelection(shoppinglistText.length());
		}
	}
	//Not used
	public void beforeTextChanged(CharSequence s, int start, int count,int after) {
	}
	//Not used
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}
}
